# Elearning 自动考试
import requests
import os
import time
import json
import random
import pandas as pd

import browser_cookie3
# from browser_cookie import load_with_keys

import requests

def get_cookie():
    cookie_str = ''
    cookie_list = None
    # cookie_list, browser = load_with_keys(
    #    '.cobo.cn', ['route', 'JSESSIONID'])
    cookie_list = browser_cookie3.edge(domain_name='elafs.cobo.cn')
    if cookie_list is None:
        return "EU=260545604;route=route=db3d55c7e464ffa40bd4ba43b8034977;JSESSIONID=58B465EA8B627C105845746268477240-n2"
    for cookie in cookie_list:
        print(cookie)
        cookie_str += cookie.name
        cookie_str += '='
        cookie_str += cookie.value
        cookie_str += '; '
    print(cookie_str)
    return cookie_str


def get_token(cookie, eid='OEH4frhoIyItqI1dKU2eGQ'):
    url = 'https://elafs.cobo.cn/m/roster/Learn/BO.cobo'
    data = 'eid=%s&action=recordEasy&param={"0":"2;0;0","1":"2;0;0","curr":1}&version=v5.0' % (
        eid)
    json_data = json.dumps(data)
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'
              }
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        if not json_text is None and 'exam' in json_text:
            json_exam = json_text['exam']
            if 'token' in json_exam:
                return 'Bearer ' + json_exam['token']

# 获取任务列表


def get_my_tasks(cookie):
    url = 'https://elafs.cobo.cn/m/ajax/myUnitasks.cobo'
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'key=&status=valid&page=0&compulsory=1&type=&version=v5.0'
    json_data = json.dumps(data)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        if not json_text is None:
            if len(json_text) > 0:
                return pd.DataFrame(json_text)

# 获取任务目录


def get_task_directory(cookie, eid):
    url = 'https://elafs.cobo.cn/m/courseware/PackageCourse/BO.cobo?action=detail&eid=%s&version=v5.0' % eid
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header)
    print(html.text)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        if not json_text is None and 'children' in json_text:
            json_children = json_text['children']
            if len(json_children) > 0 and 'children' in json_children[0]:
                json_children_children = json_children[0]['children']
                if len(json_children_children) > 0 and 'children' in json_children_children[0]:
                    json_children_children_children = json_children_children[0]['children']
                    if len(json_children_children_children) > 0:
                        df = pd.DataFrame(json_children_children_children)
                        return df

def get_single_task(cookie, eid):
    token = None
    recordeid = None
    url = 'https://elafs.cobo.cn/m/courseware/Courseware/BO.cobo?action=view&eid=%s&version=v5.0' % eid
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'eid=%s&action=recordEasy&param={"0":"2;0;0","1":"2;0;0","curr":1}&version=v5.0' % (
        eid)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.get(url, headers=header)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        if not json_text is None and 'roster_id' in json_text and 'passed' in json_text:
            return json_text['roster_id'], json_text['passed']



# 获取学习方案的一次考试记录


def get_learn_exam_record(cookie, eid):
    token = None
    recordeid = None
    url = 'https://elafs.cobo.cn/m/roster/Learn/BO.cobo'
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'eid=%s&action=recordEasy&param={"0":"2;0;0","1":"2;0;0","curr":1}&version=v5.0' % (
        eid)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        token = None
        recordeid = None
        if not json_text is None and 'exam' in json_text:
            json_exam = json_text['exam']
            if 'token' in json_exam and 'records' in json_exam:
                token = 'Bearer ' + json_exam['token']
                records = json_exam['records']
                if len(records) > 0 and 'eid' in records[0]:
                    recordeid = records[0]['eid']

    return token, recordeid

# 获取在线考试信息
def get_online_exam_record(cookie, eid):
    url = 'https://elafs.cobo.cn/m/cpaper/CPaper/BO.cobo'
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'eid=%s&action=notice&version=v5.0' % (
        eid)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        token = None
        recordeid = []
        if 'token' in json_text and 'records' in json_text:
            token = 'Bearer ' + json_text['token']
            records = json_text['records']
            if len(records) > 0 and 'eid' in records[0]:
                for record in records:
                    if 'eid' in record:
                        recordeid.append(record['eid'])
    return token, recordeid

# 开始roster考试任务
def start_task(cookie, eid):
    url = 'https://elafs.cobo.cn/m/roster/Learn/BO.cobo'
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'eid=%s&action=play&param=2&version=v5.0' % (
        eid)
    json_data = json.dumps(data)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        print(html.text)

# 结束考试


def stop_task(cookie, eid):
    url = 'https://elafs.cobo.cn/m/roster/Learn/BO.cobo'
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'eid=%s&action=quitM&param={"0":"2;0;0","1":"2;0;0","curr":1}&version=v5.0' % (
        eid)
    json_data = json.dumps(data)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        print(html.text)


# https://elafs.cobo.cn/m/courseware/PackageCourse/BO.cobo?action=detail&eid=3bIXgq4MfjXiLh3XC0grXA&version=v5.0


# 获取所有答案列表


def get_ques_answers(cookie, eid='7a1iy2FFmgq36NPx6ARUug'):
    url = 'https://elafs.cobo.cn/m/cpaper/CPaper/BO.cobo?action=detail&eid=%s&version=v5.0' % eid
    header = {'Cookie': cookie,
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    proxies = {'https': 'http://127.0.0.1:5555'}
    html = requests.get(url, headers=header)
    if html.status_code == 200:
        json_text = json.loads(html.text)
        if not json_text is None and 'ques' in json_text:
            json_ques = json_text['ques']
            if len(json_ques) > 0:
                df = pd.DataFrame(json_ques)
                df.set_index('id', drop=False, inplace=True)
                return df


def answer_ques(id, value, auth_value):
    url = 'https://api.cobo.cn/exam/answer'
    header = {'Authorization': auth_value,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'answers={"%s":%s}&version=v5.0' % (id, value)
    json_data = json.dumps(data)
    proxies = {'https': 'http://127.0.0.1:5555'}
    # html = requests.get(url headers=header, proxies=proxies, verify=False)
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        print(html.text)


def submit(auth_value):
    url = 'https://api.cobo.cn/exam/submit'
    header = {'Authorization': auth_value,
              'Content-Type': 'application/x-www-form-urlencoded',
              'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54'}
    data = 'version=v5.0'
    json_data = json.dumps(data)
    proxies = {'https': 'http://127.0.0.1:5555'}
    html = requests.post(url, headers=header, data=data)
    if html.status_code == 200:
        print(html.text)

# 在线考试任务
def do_exam_task(cookie, task_eid):
    auth_value, order_eids = get_online_exam_record(cookie, task_eid)
    time.sleep(0.01)
    # order_eids 为空 说明没有提交过，先提交一次再获取答案
    if order_eids is None or len(order_eids) == 0:
        submit(auth_value)
        auth_value, order_eids = get_online_exam_record(cookie, task_eid)
    answers = pd.DataFrame()
    for order_eid in order_eids:
        answers_once = get_ques_answers(cookie, order_eid)
        print(answers_once)
        answers = pd.concat([answers, answers_once])
    answers = answers[~answers.index.duplicated(keep='first')]
    
    # 开始回答
    print('开始答题：')
    for index, answer in answers.iterrows():
        print(answer['id'],answer['des'], answer['correctAnswer'])
        answer_ques(
            answer['id'], answer['correctAnswer'], auth_value)
        time.sleep(random.uniform(0.1,20))
    # 提交
    print('开始提交：')
    submit(auth_value)

def do_learn_task(cookie, task_eid):
    task_directorys = get_task_directory(cookie, task_eid)
    time.sleep(0.01)
    for index, child_task in task_directorys.iterrows():
        print('开始任务：', child_task['name'])
        if index > -1 and child_task['passed'] == 0:
            start_task(cookie, child_task['roster_eid'])
            child_task_roster_eid = child_task['roster_eid']
            auth_value, order_eid = get_learn_exam_record(
                cookie, child_task_roster_eid)
            time.sleep(0.01)
            # order_eid 为空 说明没有提交过，先提交一次再获取答案
            if order_eid is None:
                submit(auth_value)
                auth_value, order_eid = get_learn_exam_record(
                    cookie, child_task_roster_eid)
            answers = get_ques_answers(cookie, order_eid)
            # 开始回答
            print('开始答题：', child_task['name'])
            for index, answer in answers.iterrows():
                print(answer['id'], answer['correctAnswer'])
                answer_ques(
                    answer['id'], answer['correctAnswer'], auth_value)
                time.sleep(random.uniform(0.1,20))
            # 提交
            print('开始提交：', child_task['name'])
            submit(auth_value)
            stop_task(cookie, child_task['roster_eid'])

        time.sleep(0.01)

def do_online_learn_task(cookie, task_eid):
    child_task_roster_eid,passed  = get_single_task(cookie, task_eid)
    if passed == False:
        auth_value, order_eid = get_learn_exam_record(
            cookie, child_task_roster_eid)
        time.sleep(0.01)
        # order_eid 为空 说明没有提交过，先提交一次再获取答案
        if order_eid is None:
            submit(auth_value)
            auth_value, order_eid = get_learn_exam_record(
                cookie, child_task_roster_eid)
        answers = get_ques_answers(cookie, order_eid)
        # 开始回答
        print('开始答题：')
        for index, answer in answers.iterrows():
            print(answer['id'], answer['correctAnswer'])
            answer_ques(
                answer['id'], answer['correctAnswer'], auth_value)
            time.sleep(random.uniform(0.1,20))
        # 提交
        print('开始提交：', )
        submit(auth_value)

    time.sleep(0.01)

if __name__ == '__main__':
    cookie = get_cookie()
    tasks = get_my_tasks(cookie)
    time.sleep(0.01)
    print(tasks)
    if not tasks is None:
        for index, task in tasks.iterrows():
            task_eid = task['eid']
            if task['type'] == '在线考试':
                do_exam_task(cookie, task_eid)          
            elif task['type'] == '学习方案':
                do_learn_task(cookie, task_eid)
            elif task['type'] == '在线学习-必修':
                do_online_learn_task(cookie, task_eid)
    else:
        print("没有待完成的任务")
